import React, { Component } from 'react'
import { Button, Card, Form, Input, Layout, message, Radio, Space, Spin } from 'antd'
import './login.less'
import { getCode, loginReq } from '../../requests/login'
import { connect, ConnectedProps } from 'react-redux'
//action creator
import { loginFail, loginSuccess } from '../../actions/loginAction'
import { RouteComponentProps } from 'react-router-dom'

import { RootState } from '../../reducers'
import { Store } from 'antd/lib/form/interface'
import { getRes } from "../../configFile";
import { supervisorLogin } from "../../requests/supervisor";
import UserType from '../../types/UserType'
import AuthCode from '../../components/AuthCode'

const {
    Content,
    Footer
} = Layout

//props类型
type PropsFromRedux = ConnectedProps<typeof connector>
interface IProps extends RouteComponentProps, PropsFromRedux { }
//state类型
interface IState {
    loginLoading: boolean
    codeUrl: string
}

class Login extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            loginLoading: false,
            codeUrl: ''
        }
    }
    async componentDidMount() {
        await this.refreshAuthCode();
    }

    /*布局常量*/
    layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
    };

    tailLayout = {
        wrapperCol: { offset: 6, span: 16 },
    };

    refreshAuthCode = async (code?: string) => {
        if (!!code) {
            this.setState({
                codeUrl: code
            })
        } else {
            const codeRes = await getCode();
            this.setState({
                codeUrl: codeRes.data.svgData
            })
        }
    }

    onFinish = (values: Store): void => {
        //设置加载中
        this.setState({
            loginLoading: true
        });

        //发送请求
        (async (values: Store): Promise<void> => {
            try {
                const res = values.userType === UserType.SUPERVISOR ?
                    getRes(await supervisorLogin(values))
                    :
                    getRes(await loginReq(values))

                if (res.isSuccessful === true) {
                    // this.props.loginSuccess(values.username)
                    //跳转  登陆成功后不发送action，而在App中componentDidMount会验证登录
                    this.props.history.push('/')
                    message.success('登陆成功')
                } else {
                    this.props.loginFail()
                    //刷新验证码
                    this.refreshAuthCode(res.data)
                    //根据错误信息返回
                    if (res.message === 'wrongUserOrPassword') { message.error("用户名或密码错误") }
                    else if (res.message === 'wrongVerificationCode') { message.error("验证码错误") }
                    else message.error("登陆失败")
                }
                // }
            }
            catch (error) {
                message.error(error.toString())
            }
            finally {
                this.setState({ loginLoading: false })
            }
        })(values)
    }



    render() {
        return (
            <div className='login-layout'>
                <Layout style={{ height: '100%' }}>
                    <Content>

                        <Card className='login-card' title={<span style={{ fontWeight: 'bold' }}>用户登录</span>} bordered={true} style={{ width: 500, fontWeight: 'bold' }}>
                            <Spin spinning={this.state.loginLoading} size='large'>
                                <Form
                                    requiredMark={false}
                                    {...this.layout}
                                    name="login"
                                    initialValues={{ remember: true }}
                                    onFinish={this.onFinish}
                                >
                                    <Form.Item
                                        label="用户名"
                                        name="username"
                                        rules={[{ required: true }]}
                                    >
                                        <Input />
                                    </Form.Item>

                                    <Form.Item
                                        label="密码"
                                        name="password"
                                        rules={[{ required: true }]}
                                    >
                                        <Input.Password />
                                    </Form.Item>

                                    <Form.Item label="验证码">
                                        <Form.Item
                                            name="code"
                                            noStyle
                                            rules={[{ required: true, message: '请输入验证码' }]}
                                        >
                                            <Input autoComplete='off' />
                                        </Form.Item>
                                        <div onClick={() => { this.refreshAuthCode() }}>
                                            <AuthCode codeUrl={this.state.codeUrl} />
                                        </div>
                                    </Form.Item>

                                    <Form.Item
                                        label="管理员类型"
                                        name="userType"
                                        rules={[{ required: true }]}
                                    >
                                        <Space>
                                            <Radio.Group>
                                                <Radio value={UserType.DEVICEADMIN}>设备管理员</Radio>
                                                <Radio value={UserType.SUPERVISOR}>超级管理员</Radio>
                                            </Radio.Group>
                                        </Space>
                                    </Form.Item>

                                    <Form.Item {...this.tailLayout}>
                                        <Button type="primary" htmlType="submit">
                                            登录
                                        </Button>
                                    </Form.Item>
                                </Form>
                            </Spin>
                        </Card>

                    </Content>
                    <Footer style={{ textAlign: 'center' }}>OurEDA @2020</Footer>
                </Layout>
            </div>
        )
    }
}


//connect加入props
const mapStateToProps = (locStore: RootState) => {
    return {
        isLogin: locStore.loginReducers.isLogin
    }
}
const mapDispatchToProps = {
    loginSuccess,
    loginFail
}
const connector = connect(mapStateToProps, mapDispatchToProps)
export default connect(mapStateToProps, mapDispatchToProps)(Login)